import fs from 'fs';
import path from 'path';
import { v4 as uuidv4 } from 'uuid';
import sharp from 'sharp';

// 配置目录
const UPLOAD_DIR = path.join(process.cwd(), 'frontend/uploads');
const TEMP_DIR = path.join(process.cwd(), 'frontend/temp');

// 确保目录存在
if (!fs.existsSync(UPLOAD_DIR)) {
  fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}

if (!fs.existsSync(TEMP_DIR)) {
  fs.mkdirSync(TEMP_DIR, { recursive: true });
}

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({
      code: 405,
      message: '方法不允许'
    });
  }

  try {
    const { fileId, quality = 80, format = 'jpeg', width, height } = req.body;

    // 参数验证
    if (!fileId) {
      return res.status(400).json({
        code: 400,
        message: '文件ID不能为空'
      });
    }

    // 查找上传目录中的文件
    const files = fs.readdirSync(UPLOAD_DIR);
    const targetFile = files.find(file => file.startsWith(fileId + '_'));

    if (!targetFile) {
      return res.status(404).json({
        code: 404,
        message: '文件不存在'
      });
    }

    const filePath = path.join(UPLOAD_DIR, targetFile);
    const originalFileName = targetFile.substring(targetFile.indexOf('_') + 1);
    const fileNameWithoutExt = path.parse(originalFileName).name;
    
    // 生成输出文件路径
    const outputId = uuidv4();
    const outputFileName = `${outputId}_compressed_${fileNameWithoutExt}.${format}`;
    const outputPath = path.join(TEMP_DIR, outputFileName);

    // 使用Sharp压缩图片
    let sharpInstance = sharp(filePath);
    
    // 调整尺寸（如果提供了宽高参数）
    if (width || height) {
      sharpInstance = sharpInstance.resize({
        width: width ? parseInt(width) : undefined,
        height: height ? parseInt(height) : undefined,
        fit: 'inside',
        withoutEnlargement: true
      });
    }
    
    // 根据格式转换并压缩
    switch (format.toLowerCase()) {
      case 'jpeg':
      case 'jpg':
        sharpInstance = sharpInstance.jpeg({ quality: parseInt(quality) });
        break;
      case 'png':
        sharpInstance = sharpInstance.png({ quality: parseInt(quality) });
        break;
      case 'webp':
        sharpInstance = sharpInstance.webp({ quality: parseInt(quality) });
        break;
      default:
        sharpInstance = sharpInstance.jpeg({ quality: parseInt(quality) });
    }
    
    // 输出处理后的图片
    await sharpInstance.toFile(outputPath);
    
    // 获取压缩后的文件信息
    const stats = fs.statSync(outputPath);
    
    res.status(200).json({
      code: 200,
      message: '图片压缩成功',
      data: {
        fileId: outputId,
        fileName: outputFileName,
        size: stats.size,
        downloadUrl: `/api/file/download/${outputId}`
      }
    });
  } catch (error) {
    console.error('图片压缩异常:', error);
    res.status(500).json({
      code: 500,
      message: '图片压缩失败'
    });
  }
} 